const redis = require('../config/redis');

class VisitorService {
  constructor() {
    this.TOTAL_KEY = 'visitor:total';
    this.TODAY_KEY_PREFIX = 'visitor:daily:';
  }

  /**
   * 获取今天的日期键
   * @returns {string} 今天的日期键
   */
  getTodayKey() {
    const today = new Date().toISOString().split('T')[0]; // 格式: YYYY-MM-DD
    return `${this.TODAY_KEY_PREFIX}${today}`;
  }

  /**
   * 记录新的访问
   * @returns {Promise<Object>} 包含总访问量和今日访问量的对象
   */
  async recordVisit() {
    try {
      // 增加总访问量
      let totalCount = await redis.get(this.TOTAL_KEY) || 0;
      totalCount = parseInt(totalCount, 10) + 1;
      await redis.set(this.TOTAL_KEY, totalCount);

      // 增加今日访问量
      const todayKey = this.getTodayKey();
      let todayCount = await redis.get(todayKey) || 0;
      todayCount = parseInt(todayCount, 10) + 1;
      
      // 设置今日访问量，过期时间为48小时（确保跨天数据不会立即丢失）
      await redis.set(todayKey, todayCount, 60 * 60 * 48);

      return {
        total: totalCount,
        today: todayCount
      };
    } catch (error) {
      console.error('记录访问统计失败:', error);
      throw new Error('记录访问统计失败');
    }
  }

  /**
   * 获取访问统计数据
   * @returns {Promise<Object>} 包含总访问量和今日访问量的对象
   */
  async getVisitStats() {
    try {
      // 获取总访问量
      const totalCount = await redis.get(this.TOTAL_KEY) || 0;
      
      // 获取今日访问量
      const todayKey = this.getTodayKey();
      const todayCount = await redis.get(todayKey) || 0;

      return {
        total: parseInt(totalCount, 10),
        today: parseInt(todayCount, 10)
      };
    } catch (error) {
      console.error('获取访问统计失败:', error);
      throw new Error('获取访问统计失败');
    }
  }
}

module.exports = new VisitorService();